<script>
const tabBarLinks = [
  "pages/pintuan/pintuan",
  "pages/search/index",
  "pages/flow/index",
  "pages/my/my",
]; // 站点配置文件
import siteinfo from "./siteinfo.js"; // 工具类
import { getSceneData } from "./core/app";
import util from "@/utils/util.js";
let request = require('./utils/require');
// app.js
export default {
  data() {
    return {};
  },
  onLaunch(query) {
	  console.log("哈哈哈",this.$t('page_other.支付成功'))
	this.globalData.getLangPackage();
    // 展示本地存储能力
    const logs = uni.getStorageSync("logs") || [];
    logs.unshift(Date.now());
    uni.setStorageSync("logs", logs);
    uni.setStorageSync("web_id", siteinfo.uniacid);
    // uni.setStorageSync("referee_id", "");
	if(util.scene_decode(query.query.scene).uid >0){
		uni.setStorageSync("referee_id", util.scene_decode(query.query.scene).uid);
	}
	// #ifdef MP-WEIXIN
	this.globalData.top = wx.getMenuButtonBoundingClientRect().top;
	this.globalData.height = wx.getMenuButtonBoundingClientRect().height;
	// #endif

    uni.getSystemInfo({
      success: (res) => {
        this.globalData.navHeight = res.statusBarHeight; // 赋值导航高度
      },
      fail(err) {
        console.log(err);
      },
    }); // 登录
    uni.login({
      success: (res) => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
      },
    });
	
	this.setLangLocalData()
  },
  methods:{
	  setLangLocalData(){
		  // if(uni.getStorageSync("lang") != ''){
		  // 	this.$i18n.locale = uni.getStorageSync("lang")
		  // 	this.$i18n.setLocaleMessage(uni.getStorageSync('langData'));
		  // }
	  }

  },
  globalData: {
    payTypes: {
      WECHAT: {
        name: "微信支付",
        value: 20,
        isShow: true,
        icon: "https://zhuanyun.sllowly.cn/assets/api/images//dzx_img128.png",
      },
      BALANCE: {
        name: "余额支付",
        value: 10,
        isShow: true,
        icon: "https://zhuanyun.sllowly.cn/assets/api/images//dzx_img130.png",
      },
      HANTE: {
        name: "汉特支付",
        value: 30,
        isShow: false,
        icon: "https://zhuanyun.sllowly.cn/assets/api/images//dzx_img130.png",
      },
    },
    userInfo: null,
    navHeight: 0,
    // 声明一个全局变量用于记录小程序头部的高度
    top: "",
    height: "",
    url: siteinfo.siteroot,
    urlimg: siteinfo.siteroot + "/uploads/",
    //用户端静态文件全部存于此，减少小程序体积
    imgUrl: siteinfo.siteroot + "assets/api/images/",
    user_id: null,
	uniacid:siteinfo.uniacid,
    // api地址
    api_root: siteinfo.siteroot + "/index.php?s=/api/",
    /**
     * 小程序启动场景
     */
    onStartupScene(query) {
      // 获取场景值
	  console.log(9999999)
      let scene = this.getSceneData(query); // 记录推荐人id
      let refereeId = query.referee_id ? query.referee_id : scene.uid;
      if (refereeId > 0) {
        this.saveRefereeId(refereeId);
      }
    },
    /**
     * 获取平台ID
     */
    getWxappId() {
      return siteinfo.uniacid;
    },
    /**
     * 记录推荐人id
     */
    saveRefereeId(refereeId) {
      if (!uni.getStorageSync("referee_id")) {
        uni.setStorageSync("referee_id", refereeId);
      }
    },

    /**
     * 获取场景值(scene)
     */
    getSceneData(query) {
		console.log(query,77565)
      return query.scene ? util.scene_decode(query.scene) : {};
    },

    /**
     * 执行用户登录
     */
    doLogin(delta) {
      // 保存当前页面
      let pages = getCurrentPages();

      if (pages.length) {
        let currentPage = pages[pages.length - 1];

        if ("pages/login/login" != currentPage.route) {
          uni.setStorageSync("currentPage", currentPage);
        }
      } // 跳转授权页面

      uni.navigateTo({
        url: "/pages/login/login?delta=" + (delta || 1),
      });
    },

    /**
     * 当前用户id
     */
    getUserId() {
      return uni.getStorageSync("userInfo").user_id;
    },

    /**
     * 显示成功提示框
     */
    showSuccess(msg, callback) {
      uni.showToast({
        title: msg,
        icon: "success",
        mask: true,
        duration: 1500,

        success() {
          if (callback) {
            setTimeout(function () {
              callback();
            }, 1500);
          }
        },
      });
    },

    /**
     * 显示失败提示框
     */
    showError(msg, callback) {
      uni.showModal({
        title: "友情提示",
        content: msg,
        showCancel: false,

        success(res) {
          // callback && (setTimeout(function() {
          //   callback();
          // }, 1500));
          if (callback) {
            callback();
          }
        },
      });
    },

    /**
     * get请求
     */
    _get(url, data, success, fail, complete, check_login) {
      uni.showNavigationBarLoading();

      let _this = this; // 构造请求参数

      data = data || {};
      data.wxapp_id = _this.getWxappId(); // if (typeof check_login === 'undefined')
      //   check_login = true;
      // 构造get请求

      let request = function () {
        data.token = uni.getStorageSync("token");
        uni.request({
          url: _this.api_root + url,
          header: {
            "content-type": "application/json",
          },
          data: data,

          success(res) {
            if (res.statusCode !== 200 || typeof res.data !== "object") {
              console.log(res);

              _this.showError("网络请求出错");

              return false;
            }

            if (res.data.code === -1) {
              // 登录态失效, 重新登录
              uni.hideNavigationBarLoading();

              _this.doLogin(2);
            } else {
              if (res.data.code === 0) {
                _this.showError(res.data.msg, function () {
                  if (fail) {
                    fail(res);
                  }
                });

                return false;
              } else {
                if (success) {
                  success(res.data);
                }
              }
            }
          },

          fail(res) {
            _this.showError(res.errMsg, function () {
              if (fail) {
                fail(res);
              }
            });
          },

          complete(res) {
            uni.hideNavigationBarLoading();

            if (complete) {
              complete(res);
            }
          },
        });
      }; // 判断是否需要验证登录

      if (check_login) {
        _this.doLogin(request);
      } else {
        request();
      }
    },

    /**
     * post提交
     */
    _post_form(url, data, success, fail, complete, isShowNavBarLoading) {
      let _this = this;

      isShowNavBarLoading || true;
      data.wxapp_id = _this.getWxappId();
      data.token = uni.getStorageSync("token"); // 在当前页面显示导航条加载动画

      if (isShowNavBarLoading == true) {
        uni.showNavigationBarLoading();
      }

      uni.request({
        url: _this.api_root + url,
        header: {
          "content-type": "application/x-www-form-urlencoded",
        },
        method: "POST",
        data: data,

        success(res) {
          if (res.statusCode !== 200 || typeof res.data !== "object") {
            _this.showError("网络请求出错");

            return false;
          }

          if (res.data.code === -1) {
            // 登录态失效, 重新登录
            uni.hideNavigationBarLoading();

            _this.doLogin(1);

            return false;
          } else {
            if (res.data.code === 0) {
              _this.showError(res.data.msg, function () {
                if (fail) {
                  fail(res);
                }
              });

              return false;
            }
          }

          if (success) {
            success(res.data);
          }
        },

        fail(res) {
          // console.log(res);
          _this.showError(res.errMsg, function () {
            if (fail) {
              fail(res);
            }
          });
        },

        complete(res) {
          uni.hideNavigationBarLoading(); // wx.hideLoading();

          if (complete) {
            complete(res);
          }
        },
      });
    },

    /**
     * 验证是否存在user_info
     */
    validateUserInfo() {
      let user_info = uni.getStorageSync("user_info");
      return !!uni.getStorageSync("user_info");
    },

    /**
     * 小程序主动更新
     */
    updateManager() {
      if (!uni.canIUse("getUpdateManager")) {
        return false;
      }

      const updateManager = uni.getUpdateManager();
      updateManager.onCheckForUpdate(function (res) {
        // 请求完新版本信息的回调
        // console.log(res.hasUpdate)
      });
      updateManager.onUpdateReady(function () {
        uni.showModal({
          title: "更新提示",
          content: "新版本已经准备好，即将重启应用",
          showCancel: false,

          success(res) {
            if (res.confirm) {
              // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
              updateManager.applyUpdate();
            }
          },
        });
      });
      updateManager.onUpdateFailed(function () {
        // 新的版本下载失败
        uni.showModal({
          title: "更新提示",
          content: "新版本下载失败",
          showCancel: false,
        });
      });
    },

    /**
     * 获取tabBar页面路径列表
     */
    getTabBarLinks() {
      return tabBarLinks;
    },

    /**
     * 跳转到指定页面
     * 支持tabBar页面
     */
    navigationTo(url) {
      if (!url || url.length == 0) {
        return false;
      }

      let tabBarLinks = this.getTabBarLinks(); // tabBar页面

      if (tabBarLinks.indexOf(url) > -1) {
        uni.switchTab({
          url: "/" + url,
        });
      } else {
        // 普通页面
        uni.navigateTo({
          url: "/" + url,
        });
      }
    },

    /**
     * 记录formId
     * (因微信模板消息已下线，所以formId取消不再收集)
     */
    saveFormId(formId) {
      return true; // let _this = this;
      // console.log('saveFormId');
      // if (formId === 'the formId is a mock one') {
      //   return false;
      // }
      // _this._post_form('wxapp.formId/save', {
      //   formId: formId
      // }, null, null, null, false);
    },

    /**
     * 生成转发的url参数
     */
    getShareUrlParams(params) {
      let _this = this;

      return util.urlEncode(
        Object.assign(
          {
            referee_id: _this.getUserId(),
          },
          params
        )
      );
    },

    /**
     * 发起微信支付
     */
    wxPayment(option) {
      let options = Object.assign(
        {
          payment: {},
          success: () => {},
          fail: () => {},
          complete: () => {},
        },
        option
      );
      uni.requestPayment({
        timeStamp: options.payment.timeStamp,
        nonceStr: options.payment.nonceStr,
        package: "prepay_id=" + options.payment.prepay_id,
        signType: "MD5",
        paySign: options.payment.paySign,

        success(res) {
          options.success(res);
        },

        fail(res) {
          options.fail(res);
        },

        complete(res) {
          options.complete(res);
        },
      });
    },

    /**
     * 验证登录
     */
    checkIsLogin() {
      return (
        uni.getStorageSync("token") != "" && uni.getStorageSync("user_id") != ""
      );
    },

    /**
     * 授权登录
     */
    getUserInfo(e, callback) {
      let App = this;

      if (e.detail.errMsg !== "getUserInfo:ok") {
        return false;
      }

      uni.showLoading({
        title: "正在登录",
        mask: true,
      }); // 执行微信登录

      uni.login({
        success(res) {
          // 发送用户信息
          App._post_form(
            "user/login",
            {
              code: res.code,
              user_info: e.detail.rawData,
              encrypted_data: e.detail.encryptedData,
              iv: e.detail.iv,
              signature: e.detail.signature,
              referee_id: uni.getStorageSync("referee_id"),
            },
            (result) => {
              // 记录token user_id
              uni.setStorageSync("token", result.data.token);
              uni.setStorageSync("user_id", result.data.user_id); // 执行回调函数

              if (callback) {
                callback();
              }
            },
            false,
            () => {
              uni.hideLoading();
            }
          );
        },
      });
    },
    // 检测系统语言
    checkLocalLanguage() {
      // en、zh-Hans、zh-Hant、fr、es
      const appLanguage = uni.getSystemInfoSync().appLanguage;
	  console.log(appLanguage,86)
      // 系统默认 zh-Hans（中文）
      if (appLanguage === "zh-Hans") {
        uni.showModal({
          content:
            "检测到系统语言与当前语言不一致，是否前往切换语言 \n If the system language is inconsistent with the current language, go to the switch language",
          success(res) {
            if (res.confirm) {
              uni.navigateTo({
                url: "/pages/switchLanguage/index",
              });
            }
          },
        });
      }
    },
	//获取默认语言
	getLangPackage() {
		let that = this
		var wxapp_id = siteinfo.uniacid

		//动态插入内容到i18n
		// wx.$vm.$i18n.setLocaleMessage(type,resE.data.data);
		request.get(`index.php?s=/api/page/getLangSetting&wxapp_id=` + wxapp_id).then(res => {
			if (res.data.code == 1) {
					const that = this;
					var type = res.data.data.default;
					if(uni.getStorageSync("lang") != ''){
						type = uni.getStorageSync("lang")
					}
					request
						.post(`index.php?s=/api/page/getLangPackage&wxapp_id=` + uni.getStorageSync('web_id'), {
							type: type
						})
						.then(resE => {
							if (resE.data.code == 1) {
								console.log(resE.data.data,23)
								uni.setStorageSync('langData',resE.data.data)
								//动态插入内容到i18n
								wx.$vm.$i18n.setLocaleMessage(type,resE.data.data);
								//本地语言开关切换
								wx.$vm.$i18n.locale = type;
								uni.setStorageSync('lang',type)
							}
							uni.hideLoading();
						});
				
			}
		}); 
	},
  },
};
</script>
<style>
@import "./app.css";
</style>
